package com.project.filetsystem.service.impl;

import com.project.filetsystem.service.IVideoService;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.nio.cs.UTF_32LE;


import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.net.URL;

/**
 * @description: 获取视频帧，生成图片
 * @author zyb
 * @date 2020-07-12
 */
@Slf4j
@Service
public class VideoServiceImpl implements IVideoService {
    @Value("file.url")
    private String fileUrl;
    @Override
    public String getImageNameByFolderName(String folderPath,String voidPath) throws Exception {
        String imagePath = folderPath+"\\"+voidPath.substring(0,voidPath.indexOf("."))+".jpg";
        File imageFile = new File(imagePath);
        if(!imageFile.exists()){
            getVideoPicture(folderPath+"/"+voidPath,folderPath+"/");
        }
        String url = imagePath.substring(fileUrl.trim().length()-5, imagePath.length()).replace("\\","_");
        log.info("url:{}",url);
        return url;
    }

    /**
     * 获取视频第一帧
     * @param videoPath 视频地址
     * @param imgPath 生成图片的名字（包含全路径）
     * @throws Exception
     */
    @Override
    public void getVideoPicture(String videoPath,String imgPath) throws Exception{
        File imgFile = new File(imgPath);
        //判断保存的文件的文件夹是否存在，不存在创建。
        File imageFile = new File(videoPath.replace(".mp4",".jpg"));
        if(imageFile.exists()){
            return;
        }
        if (!imgFile.getParentFile().exists()) {
            log.info("保存文件的文件夹不存在，创建。");
            imgFile.getParentFile().mkdirs();
        }
        log.info("imgFile:{}",imgFile);
        File videoFile = new File(videoPath);
        if (videoFile.exists()) {
            log.info("视频存在：{}",videoFile);
            //实例化“截取视频首帧”对象
            FFmpegFrameGrabber ff = new FFmpegFrameGrabber(videoFile);
            ff.start();
            int ftp = ff.getLengthInFrames();
            int flag=0;
            Frame frame = null;
            while (flag <= ftp) {
                //获取帧
                frame = ff.grabImage();
                //过滤前1帧，避免出现全黑图片
                if ((flag>1)&&(frame != null)) {
                    break;
                }
                flag++;
            }
            //后期更具不同视频类型需要修改代码 date:2022-10-23 version:v1
            String videoName = videoPath.replace(".mp4",".jpg");

            ImageIO.write(frameToBufferedImage(frame), "jpg", new File(videoName));
            ff.close();
            ff.stop();
        }else {
            log.info("视频不存在：{}",videoFile);
        }
    }

    /**
     * 帧转为流
     * @param frame
     * @return
     */
    private static RenderedImage frameToBufferedImage(Frame frame) {
        //创建BufferedImage对象
        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage bufferedImage = converter.getBufferedImage(frame);
        return bufferedImage;
    }

    private void initFileName(){

    }

}
